package com.free.explayer.files;


import android.app.Activity;
import android.content.Context;
import android.os.Environment;

import androidx.core.app.ActivityCompat;

import java.io.File;
import java.util.ArrayList;

public class FileHelper {

    private static final String TAG = "FileHelper";
    private ArrayList<String> mMusicList;
    private Context mContext;

    public FileHelper(Context context) {
        mContext = context;
    }

    /**
     * @return 如果失败返回null。
     */
    private File getMusicFileDir() {
        if (isMounted()) {
            return mContext.getExternalFilesDir(Environment.DIRECTORY_MUSIC);
        }
        return null;
    }

    private boolean isMounted() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    private void initPlayerList() {
        if (mMusicList == null) {
            mMusicList = new ArrayList<>();
        } else {
            mMusicList.clear();
        }
        File[] files = getMusicFileDir().listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                mMusicList.add(file.getAbsolutePath());
            }
        }
    }

    public String firstMusic() {
        if (mMusicList == null || mMusicList.isEmpty()) {
            initPlayerList();
        }
        if (mMusicList != null && mMusicList.size() > 0) {
            String path = mMusicList.get(0);
            File file = new File(path);
            if (file.exists() && file.isFile()) {
                return path;
            }
        }
        throw new RuntimeException("get firstMusic error");
    }
}
